//
//  SinaStatusListViewModel.swift
//  weibo
//
//  Created by liuchao on 16/1/25.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class SinaStatusListViewModel: NSObject {

    lazy var list:[SinaStatusViewModel] = [SinaStatusViewModel]()
    
    func getData(success:()->(),failure:()->()){
    
        // 1 创建一个 afn实例
        let afn = AFHTTPSessionManager()
        
        // 2 拼接参数
        //access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得
        let params = ["access_token":SinaAccountViewModel.shareInstance.access_token]
        
        SVProgressHUD.show()
        // 3 发送一个 get 请求
        afn.GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, success: { (_, JSON) -> Void in
            //            printLog(JSON)
            
            SVProgressHUD.dismiss()
            
            if let dic = JSON as? [String: AnyObject]{
                
                // 一定要确保有数据,再强制解包
                let statues = dic["statuses"] as! [[String: AnyObject]]
                
                // 便利
                for status in statues {
                    
                    let statusModel = SinaStatusModel(dict: status)
                    
                    // 添加到数组里
                    self.list.append(SinaStatusViewModel(statusModel: statusModel))
                    
                    ///Reference to property 'list' in closure requires explicit 'self.' to make capture semantics explicit
                }
                
                // 刷新UI
//                self.tableView.reloadData()
                success()
                
            }
            
            }) { (_ , error) -> Void in
                printLog(error)
                
                SVProgressHUD.showErrorWithStatus(error.description)
        }
    }
    
   

}
